import store from '../store'
let server_url = ''
let token = ''
server_url = process.env.NODE_ENV === 'development' ? 'https://api.zhuishushenqi.com' : 'https://tapi.wujiyunhe.cn'
// server_url = process.env.NODE_ENV === 'development' ? 'http://10.0.5.106:8080' : 'http://***/api'
export const DOMAIN = server_url
export const SUCCESS = 1
export const UNAUTHORIZED = 2

function request(options = {}) {
	store.state.user.token && (token = store.state.user.token)
	options.url = options.url.includes('http')?options.url:`${server_url}${options.url}`
	//配置请求头
	options.header = {
		// 'content-type': options.contentType?options.contentType:'application/json',
		// 'content-type': options.contentType?options.contentType:'application/x-www-form-urlencoded',
		// 'Authorization': token?'Bearer ' + token:''
    };
    return new Promise((resolved, rejected) => {
        options.success = (res) => {
			options.showLoading && uni.hideLoading()
			if (res.data.status == SUCCESS||res.statusCode == 200) {  //请求成功
				// console.log('23',res)
			    resolved(res.data);
			} else {
				console.log(res)
				if(res.data.status == UNAUTHORIZED){
					uni.redirectTo({
						url:'/pages/login/index?curl='+encodeURIComponent(getCurrentPages().slice(-1)[0].route)
					})
				}
				setTimeout(() => {
					uni.showToast({
						icon: 'none',
						duration: 3000,
						title: `${res.data.msg}`
					});
				}, 1000)
		    	rejected(res.data.msg); //错误
			}
        }
	    //错误
        options.fail = (err) => {
			options.showLoading && uni.hideLoading()
			uni.showToast({
			    icon: 'none',
			    duration: 3000,
			    title: `无法连接网络`
			});
            rejected(err); //错误
        }
		options.showLoading && uni.showLoading({
			title: '加载中...',
			mask: true
		})
        uni.request(options);

    });
}
export default request;
